import axios from "@/request/request";

const state = {
  userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
  token: localStorage.getItem('token')
}
const mutations = {
  updateUserInfo(state, userInfo) {
    state.userInfo = userInfo
  }
}
const actions = {
  // 邮箱登录
  async emailUserLogin({ commit }, { email, password }) {
    const { data: res } = await axios.post(`/login?email=${email}@163.com&password=${password}`)
    if (res.code == 200) {
      commit('updateUserInfo', res.profile)
      localStorage.setItem('userInfo', JSON.stringify(res.profile))
      localStorage.setItem('token', res.token)
      return 'success'
    }
  },
  // 获取用户信息
  async getUserInfo({ commit }) {
    const { data: res } = await axios.get('/user/account')
    if (res.code == 200) {
      commit('updateUserInfo', res.profile)
      localStorage.setItem('userInfo', JSON.stringify(res.profile))
      localStorage.setItem('token', res.token)
      return 'success'
    }
  }
}
const getters = {
  userId(state) {
    return state.userInfo.userId
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}